//
//  FileWriter.m
//  ImageReplacer
//
//  Created by Tyler Powell on 4/30/12.
//  Copyright 2012 Georgia Institute of Technology. All rights reserved.
//

#import "FileWriter.h"
#import <stdlib.h>


@implementation FileWriter

@synthesize images;
@synthesize enbuttons;
@synthesize disbuttons;
@synthesize options;
@synthesize launchers;

BOOL writeiLoLFile(NSString* fileName, NSString* write){
	
	createFile(fileName);
	
	NSFileHandle *file;
	
	//data = [NSMutableData dataWithBytes:bytestring length:strlen(bytestring)];
	NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
	resourcePath = [resourcePath stringByAppendingString:@"/"];
	NSString* filePath = [resourcePath stringByAppendingString:fileName];
	
	file = [NSFileHandle fileHandleForUpdatingAtPath: filePath];
	NSMutableString* fileMutable = [NSMutableString stringWithString:write];
	NSString* fileType = [fileMutable substringFromIndex:[fileMutable length]-4];
	//NSLog(fileType);
	if (file == nil || ![fileType isEqualToString:@".app"]){
		//NSLog(@"Failed to open iLoL location");
		//create an error dialog box here
		return NO;
	}
	
	NSArray* lines = getLines(fileName);
	NSMutableArray* mutableLines = [NSMutableArray arrayWithArray:lines];
	[mutableLines replaceObjectAtIndex:0 withObject:write];
	write = linesToString(mutableLines);
	
	//write = [write stringByAppendingString:@"\n"];
	//[file seekToEndOfFile];
	[file writeData:[write dataUsingEncoding:NSUTF8StringEncoding]];
	
	[file closeFile];
	
	return YES;
	
}
BOOL writeFile(NSString* fileName, NSString* write)
{
	
	createFile(fileName);
	
	NSFileHandle *file;
	
	//data = [NSMutableData dataWithBytes:bytestring length:strlen(bytestring)];
	NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
	resourcePath = [resourcePath stringByAppendingString:@"/"];
	NSString* filePath = [resourcePath stringByAppendingString:fileName];
	
	file = [NSFileHandle fileHandleForUpdatingAtPath: filePath];
	NSMutableString* fileMutable = [NSMutableString stringWithString:write];
	NSString* fileType = [fileMutable substringFromIndex:[fileMutable length]-4];
	//NSLog(fileType);
	if (file == nil || ![fileType isEqualToString:@".png"]){
		//NSLog(@"Failed to open file");
		//create an error dialog box here
		return NO;
	}
    NSMutableArray* fileStuffs = [NSMutableArray arrayWithArray:getLines(fileName)];
    [fileStuffs addObject:write];
    [fileStuffs sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    NSString* postSort = linesToString(fileStuffs);
	[file truncateFileAtOffset:0];
	[file writeData:[postSort dataUsingEncoding:NSUTF8StringEncoding]];
	
	
	//[file seekToFileOffset: 10];
	
	//[file writeData: data];
	
	[file closeFile];
	
	return YES;
}
BOOL createFile(NSString* fileName){
	NSFileManager *filemgr;
	
	filemgr = [NSFileManager defaultManager];
	NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
	resourcePath = [resourcePath stringByAppendingString:@"/"];
	NSString* filePath = [resourcePath stringByAppendingString:fileName];
	if ([filemgr fileExistsAtPath: filePath ])
		return YES;
	else{
		[filemgr createFileAtPath:filePath contents:nil attributes:nil];
        NSLog (@"File not found, creating file");
		return NO;
	}
	
}

int countLines(NSString* fileName){
	NSFileManager *filemgr;
	filemgr = [NSFileManager defaultManager];
	NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
	resourcePath = [resourcePath stringByAppendingString:@"/"];
	NSString* filePath = [resourcePath stringByAppendingString:fileName];
	NSData* dataBuffer;
	if ([filemgr fileExistsAtPath: filePath ] == YES){
		dataBuffer = [filemgr contentsAtPath:filePath];
		NSString *contents = [[NSString alloc] initWithData:dataBuffer encoding:NSASCIIStringEncoding];
		//NSLog(contents);
		NSArray* imagePaths = [contents componentsSeparatedByString:@"\n"];
		/*
		for(int i = 0; i < [imagePaths count]-1; i++){
			NSLog([imagePaths objectAtIndex:i]);
		}
		 */
		[contents release];
		return [imagePaths count];
	}
	else{
		[filemgr createFileAtPath:filePath contents:nil attributes:nil];
        NSLog (@"File not found, creating file");
		return 0;
	}
}

BOOL replacePatcherImage(NSString* fileName, BOOL random){
	NSFileManager *filemgr;
	filemgr = [NSFileManager defaultManager];
	NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
	resourcePath = [resourcePath stringByAppendingString:@"/"];
	NSString* filePath = [resourcePath stringByAppendingString:fileName];
	NSData* dataBuffer;
	if ([filemgr fileExistsAtPath: filePath ] == YES){
		dataBuffer = [filemgr contentsAtPath:filePath];
		NSString *contents = [[NSString alloc] initWithData:dataBuffer encoding:NSASCIIStringEncoding];
		//NSLog(contents);
		NSArray* imagePaths = [contents componentsSeparatedByString:@"\n"];
		if ([imagePaths count] <=1) {
            [contents release];
			return NO;
		}
		[imagePaths removeObjectAtIndex:[imagePaths count]-1];

		NSString *imgPath;
        if (random) {
            int imgNum = arc4random()%[imagePaths count];
            imgPath = [imagePaths objectAtIndex:imgNum];
        } else {
            //NSLog(@"not random");
            imgPath = getItemFromFileAtIndex(@"options.txt", 1);
            if (![filemgr fileExistsAtPath:imgPath]) {
                [contents release];
                return NO;
            }
        }
        
        NSString *lolPath = getItemFromFileAtIndex(@"options.txt", 0);
		lolPath = [lolPath stringByAppendingString:@"/Contents/Resources/background.png"];
        if ([filemgr fileExistsAtPath:lolPath]) {
            [filemgr removeFileAtPath:lolPath handler:nil];
        }
        [filemgr copyItemAtPath:imgPath toPath:lolPath error:nil];
		
		
		[contents release];
		return YES;
	}
	else{
		[filemgr createFileAtPath:filePath contents:nil attributes:nil];
        NSLog (@"File not found, creating file");
		return NO;
	}
	
}

BOOL replaceFile(NSString* fileName, NSString* fileToReplace, int index){
	NSFileManager *filemgr;
	filemgr = [NSFileManager defaultManager];
	NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
	resourcePath = [resourcePath stringByAppendingString:@"/"];
	NSString* filePath = [resourcePath stringByAppendingString:fileName];
	NSData* dataBuffer;
	if ([filemgr fileExistsAtPath: filePath ] == YES){
		dataBuffer = [filemgr contentsAtPath:filePath];
		NSString *contents = [[NSString alloc] initWithData:dataBuffer encoding:NSASCIIStringEncoding];
		//NSLog(contents);
		NSArray* imagePaths = [contents componentsSeparatedByString:@"\n"];
		if ([imagePaths count] <=1) {
            [contents release];
			return NO;
		}
		[imagePaths removeObjectAtIndex:[imagePaths count]-1];
        
		NSString *imgPath;
        imgPath = getItemFromFileAtIndex(@"options.txt", index);
        if (![filemgr fileExistsAtPath:imgPath]) {
            [contents release];
            return NO;
        }
        
        NSString *lolPath = getItemFromFileAtIndex(@"options.txt", 0);
		lolPath = [lolPath stringByAppendingString:@"/Contents/Resources/"];
        lolPath = [lolPath stringByAppendingString:fileToReplace];
        if ([filemgr fileExistsAtPath:lolPath]) {
            [filemgr removeFileAtPath:lolPath handler:nil];
        }
        [filemgr copyItemAtPath:imgPath toPath:lolPath error:nil];
		
		
		[contents release];
		return YES;
	}
	else{
		[filemgr createFileAtPath:filePath contents:nil attributes:nil];
        NSLog (@"File not found, creating file");
		return NO;
	}
	
}

NSArray* getImageFiles(NSString* fileName){
	NSFileManager *filemgr;
	filemgr = [NSFileManager defaultManager];
	NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
	resourcePath = [resourcePath stringByAppendingString:@"/"];
	NSString* filePath = [resourcePath stringByAppendingString:fileName];
	NSData* dataBuffer;
	if ([filemgr fileExistsAtPath: filePath ] == YES){
		dataBuffer = [filemgr contentsAtPath:filePath];
		NSString *contents = [[NSString alloc] initWithData:dataBuffer encoding:NSASCIIStringEncoding];
		//NSLog(contents);
		NSArray* imagePaths = [contents componentsSeparatedByString:@"\n"];
		[contents release];
		return imagePaths;
	}
	else{
		[filemgr createFileAtPath:filePath contents:nil attributes:nil];
        NSLog (@"File not found, creating file");
		return nil;
	}
}

NSArray* getLines(NSString* fileName){
	return getImageFiles(fileName);
}

NSString* linesToString(NSArray* lines){
	NSString* string = @"";
	for(int i = 0; i<[lines count]; i++){
		//NSLog(string);
		if(![[lines objectAtIndex:i] isEqualToString:@""]){
			string = [string stringByAppendingString:[lines objectAtIndex:i]];
			string = [string stringByAppendingString:@"\n"];
		}
	}
	return string;
}

NSString* linesToStringWithEmptyStrings(NSArray* lines){
    NSString* string = @"";
    for(int i = 0; i<[lines count]; i++){
        //NSLog(string);
        string = [string stringByAppendingString:[lines objectAtIndex:i]];
        string = [string stringByAppendingString:@"\n"];
    }
    return string;
}

BOOL fileContains(NSString* fileName, NSString* itemName){
	NSArray* lines = getLines(fileName);
	for(int i = 0; i < [lines count]; i++){
		if([[lines objectAtIndex:i] isEqualToString:itemName])
			return YES;
	}
	return NO;
}

BOOL removeItemFromFile(NSString* fileName, int index){
	NSArray* lines = getLines(fileName);
	if(index > [lines count]-1)
		return NO;
	NSMutableArray* mutableLines = [NSMutableArray arrayWithArray:lines];
	[mutableLines removeObjectAtIndex:index];
	NSString* write = linesToString(mutableLines);
	NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
	resourcePath = [resourcePath stringByAppendingString:@"/"];
	NSString* filePath = [resourcePath stringByAppendingString:fileName];
	NSFileHandle* file = [NSFileHandle fileHandleForUpdatingAtPath: filePath];
	[file truncateFileAtOffset:0];
	[file writeData:[write dataUsingEncoding:NSUTF8StringEncoding]];
	return YES;
}

NSString* getItemFromFileAtIndex(NSString* fileName, int index){
	NSArray* lines = getLines(fileName);
	if(index > [lines count]-1)
		return nil;
	return [lines objectAtIndex:index];
}

void writeToFileAtIndex(NSString* fileName, NSString* line, int index){
	NSArray* lines = getLines(fileName);
	NSMutableArray* mutableLines = [NSMutableArray arrayWithArray:lines];
    //NSLog(@"lines: %d",[lines count]);
	if(index > [lines count]-1){
		[mutableLines addObject:line];
	} else {
		[mutableLines replaceObjectAtIndex:index withObject:line];
	}
    NSString* write;
    if ([fileName isEqualToString:@"options.txt"]) {
        if ([[mutableLines lastObject] isEqualToString:@""]) {
            [mutableLines removeLastObject];
        }
        write = linesToStringWithEmptyStrings(mutableLines);
        //NSLog(write);
    } else {
        write = linesToString(mutableLines);
        //NSLog(write);
    }
	//NSLog(write);
	NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
	resourcePath = [resourcePath stringByAppendingString:@"/"];
	NSString* filePath = [resourcePath stringByAppendingString:fileName];
	NSFileHandle* file = [NSFileHandle fileHandleForUpdatingAtPath: filePath];
	[file truncateFileAtOffset:0];
	[file writeData:[write dataUsingEncoding:NSUTF8StringEncoding]];
	
}

void initializeOptions(){
    NSArray* initial = [NSArray arrayWithObjects:@"",@"",@"1",@"",@"",@"",@"",@"Do not change this file!",nil];
    NSString* write = linesToStringWithEmptyStrings(initial);
	NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
	resourcePath = [resourcePath stringByAppendingString:@"/"];
	NSString* filePath = [resourcePath stringByAppendingString:@"options.txt"];
	NSFileHandle* file = [NSFileHandle fileHandleForUpdatingAtPath: filePath];
	[file truncateFileAtOffset:0];
	[file writeData:[write dataUsingEncoding:NSUTF8StringEncoding]];
}

//Start of new file writing
-(id) init
{
    if(self = [super init])
    {
        NSFileManager* manager = [NSFileManager defaultManager];
        imagesPath = [FileWriter stringWithResourcePath:@"images.xml"];
        enbuttonsPath = [FileWriter stringWithResourcePath:@"enbuttons.xml"];
        disbuttonsPath= [FileWriter stringWithResourcePath:@"disbuttons.xml"];
        optionsPath = [FileWriter stringWithResourcePath:@"options.xml"];
        launchersPath = [FileWriter stringWithResourcePath:@"launchers.xml"];
        if([manager fileExistsAtPath:imagesPath]){
            images = [FileWriter deserializeArrayFromFile:@"images.xml"];
            //NSLog(@"Images contents: \n%@",images);
        }
        else {
            images = [[NSMutableArray alloc] init];
        }
        if([manager fileExistsAtPath:enbuttonsPath])
            enbuttons = [FileWriter deserializeArrayFromFile:@"enbuttons.xml"];
        else {
            enbuttons = [[NSMutableArray alloc] init];
        }
        if([manager fileExistsAtPath:disbuttonsPath])
            disbuttons = [FileWriter deserializeArrayFromFile:@"disbuttons.xml"];
        else {
            disbuttons = [[NSMutableArray alloc] init];
        }
        if([manager fileExistsAtPath:optionsPath])
            options = [FileWriter deserializeArrayFromFile:@"options.xml"];
        else {
            options = [[NSMutableArray arrayWithObjects:@"",@"",@"1",@"",@"",@"",@"", nil] retain];
            //[self saveOptions];
        }
        if([manager fileExistsAtPath:launchersPath])
            launchers = [FileWriter deserializeArrayFromFile:@"launchers.xml"];
        else {
            launchers = [[NSMutableArray alloc] init];
        }
    }
    return self;
}

-(void) addImage:(NSString*)filePath
{
    if (![images containsObject:filePath]) {
        [images addObject:filePath];
        [images sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
        [self saveImages];
    } else {
        NSLog(@"Already contains %@", filePath);
    }
    
}
-(void) addEnabledButton:(NSString*)filePath
{
    if (![enbuttons containsObject:filePath]) {
        [enbuttons addObject:filePath];
        [enbuttons sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
        [self saveEnabledButtons];
    } else {
        NSLog(@"Already contains %@", filePath);
    }
}
-(void) addDisabledButton:(NSString*)filePath
{
    if (![disbuttons containsObject:filePath]){
        [disbuttons addObject:filePath];
        [disbuttons sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
        [self saveDisabledButtons];
    } else {
        NSLog(@"Already contains %@", filePath);
    }
}
-(void) addLauncher:(NSString*)filePath
{
    if (![launchers containsObject:filePath]) {
        [launchers addObject:filePath];
        [launchers sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
        [self saveLaunchers];
    }
}

-(void) removeImage:(NSInteger)index
{
    [images removeObjectAtIndex:index];
    [self saveImages];
}
-(void) removeEnabledButton:(NSInteger)index
{
    [enbuttons removeObjectAtIndex:index];
    [self saveEnabledButtons];
}
-(void) removeDisabledButton:(NSInteger)index
{
    [disbuttons removeObjectAtIndex:index];
    [self saveDisabledButtons];
}

-(void) removeLauncher:(NSInteger)index
{
    [launchers removeObjectAtIndex:index];
    [self saveLaunchers];
}

-(void) replaceImageAtIndex:(NSInteger)index withImage:(NSString*) newImage
{
    [images replaceObjectAtIndex:index withObject:newImage];
    [images sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    [self saveImages];
}
-(void) replaceEnabledButtonAtIndex:(NSInteger)index withImage:(NSString*) newImage
{
    [enbuttons replaceObjectAtIndex:index withObject:newImage];
    [enbuttons sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    [self saveEnabledButtons];
}
-(void) replaceDisabledButtonAtIndex:(NSInteger)index withImage:(NSString*) newImage
{
    [disbuttons replaceObjectAtIndex:index withObject:newImage];
    [disbuttons sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    [self saveDisabledButtons];
}

-(void) replaceOptionAtIndex:(NSInteger)index withOption:(id)newOption
{
    [options replaceObjectAtIndex:index withObject:newOption];
    [self saveOptions];
}
-(void) replaceLauncherAtIndex:(NSInteger)index withLauncher:(NSString*)newLauncher
{
    [launchers replaceObjectAtIndex:index withObject:newLauncher];
    [self saveLaunchers];
}

-(void) saveImages
{
    [FileWriter serializeArrayToFile:@"images.xml" array:images];
}
-(void) saveEnabledButtons
{
    [FileWriter serializeArrayToFile:@"enbuttons.xml" array:enbuttons];
}
-(void) saveDisabledButtons
{
    [FileWriter serializeArrayToFile:@"disbuttons.xml" array:disbuttons];
}
-(void) saveOptions
{
    [FileWriter serializeArrayToFile:@"options.xml" array:options];
}
-(void) saveLaunchers
{
    [FileWriter serializeArrayToFile:@"launchers.xml" array:launchers];
}

-(BOOL) needsUpdate
{
    if ([[[[NSBundle mainBundle] bundlePath] lastPathComponent] isEqualToString:@"temp.app"]) {
        return YES;
    }
    //NSArray *version = [NSArray arrayWithObject:@"1"];
    //[FileWriter serializeArrayToFile:@"version.xml" array:version];
    NSString *versionFile = @"http://dl.dropbox.com/u/62684750/temp.app/Contents/Resources/version.xml";
    NSURLResponse *response = nil;
    NSError *err = nil;
    NSData *versionData = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:versionFile]] returningResponse:&response error:&err];
    if(!versionData){
        NSLog(@"No internet connection, cannot check versions");
        return NO;
    }
    NSLog(@"%@", err);
    NSPropertyListFormat format;
    NSError *error;
    NSArray *version = [NSPropertyListSerialization propertyListWithData:versionData options:NSPropertyListMutableContainers format:&format error:&error];
    NSLog(@"%@",version);
    NSInteger var = [[version objectAtIndex:0] longLongValue];
    NSLog(@"%d",var);
    NSArray *current = [FileWriter deserializeArrayFromFile:@"version.xml"];
    return (var>[[current objectAtIndex:0] longLongValue]);
}

-(void) updateApp
{
    NSError *err = nil;
    
    NSString *appName = [[[NSBundle mainBundle] bundlePath] lastPathComponent];
    NSString *currentRes = [[NSBundle mainBundle] resourcePath];
    //NSLog(appName);
    if ([appName isEqualToString:@"temp.app"]) {
        NSString *prevApp = @"/Applications/PatcherReplacer.app";
        NSString *resources = nil;
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:prevApp]) {
            resources = [prevApp stringByAppendingPathComponent:@"Contents/Resources"];
            if ([[NSFileManager defaultManager] fileExistsAtPath:[resources stringByAppendingPathComponent:@"images.xml"]])
                [[NSFileManager defaultManager] moveItemAtPath:[resources stringByAppendingPathComponent:@"images.xml"] toPath:[currentRes stringByAppendingPathComponent:@"images.xml"] error:&err];
            if ([[NSFileManager defaultManager] fileExistsAtPath:[resources stringByAppendingPathComponent:@"enbuttons.xml"]])
                [[NSFileManager defaultManager] moveItemAtPath:[resources stringByAppendingPathComponent:@"enbuttons.xml"] toPath:[currentRes stringByAppendingPathComponent:@"enbuttons.xml"] error:&err];
            if ([[NSFileManager defaultManager] fileExistsAtPath:[resources stringByAppendingPathComponent:@"disbuttons.xml"]])
                [[NSFileManager defaultManager] moveItemAtPath:[resources stringByAppendingPathComponent:@"disbuttons.xml"] toPath:[currentRes stringByAppendingPathComponent:@"disbuttons.xml"] error:&err];
            if ([[NSFileManager defaultManager] fileExistsAtPath:[resources stringByAppendingPathComponent:@"options.xml"]])
                [[NSFileManager defaultManager] moveItemAtPath:[resources stringByAppendingPathComponent:@"options.xml"] toPath:[currentRes stringByAppendingPathComponent:@"options.xml"] error:&err];
            if ([[NSFileManager defaultManager] fileExistsAtPath:[resources stringByAppendingPathComponent:@"launchers.xml"]])
                [[NSFileManager defaultManager] moveItemAtPath:[resources stringByAppendingPathComponent:@"launchers.xml"] toPath:[currentRes stringByAppendingPathComponent:@"launchers.xml"] error:&err];
            
        } else if([[NSFileManager defaultManager] fileExistsAtPath:[[@"~" stringByAppendingString:prevApp] stringByExpandingTildeInPath]])
        {
            prevApp = [[@"~" stringByAppendingString:prevApp] stringByExpandingTildeInPath];
            resources = [prevApp stringByAppendingPathComponent:@"Contents/Resources"];
            if ([[NSFileManager defaultManager] fileExistsAtPath:[resources stringByAppendingPathComponent:@"images.xml"]])
                [[NSFileManager defaultManager] moveItemAtPath:[resources stringByAppendingPathComponent:@"images.xml"] toPath:[currentRes stringByAppendingPathComponent:@"images.xml"] error:&err];
            if ([[NSFileManager defaultManager] fileExistsAtPath:[resources stringByAppendingPathComponent:@"enbuttons.xml"]])
                [[NSFileManager defaultManager] moveItemAtPath:[resources stringByAppendingPathComponent:@"enbuttons.xml"] toPath:[currentRes stringByAppendingPathComponent:@"enbuttons.xml"] error:&err];
            if ([[NSFileManager defaultManager] fileExistsAtPath:[resources stringByAppendingPathComponent:@"disbuttons.xml"]])
                [[NSFileManager defaultManager] moveItemAtPath:[resources stringByAppendingPathComponent:@"disbuttons.xml"] toPath:[currentRes stringByAppendingPathComponent:@"disbuttons.xml"] error:&err];
            if ([[NSFileManager defaultManager] fileExistsAtPath:[resources stringByAppendingPathComponent:@"options.xml"]])
                [[NSFileManager defaultManager] moveItemAtPath:[resources stringByAppendingPathComponent:@"options.xml"] toPath:[currentRes stringByAppendingPathComponent:@"options.xml"] error:&err];
            if ([[NSFileManager defaultManager] fileExistsAtPath:[resources stringByAppendingPathComponent:@"launchers.xml"]])
                [[NSFileManager defaultManager] moveItemAtPath:[resources stringByAppendingPathComponent:@"launchers.xml"] toPath:[currentRes stringByAppendingPathComponent:@"launchers.xml"] error:&err];
        } else {
            return;
        }
        
        NSString *newPath = [[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"PatcherReplacer.app"];
        if ([[NSFileManager defaultManager]fileExistsAtPath:newPath]) {
            [[NSFileManager defaultManager]removeItemAtPath:newPath error:&err];
        }
        [[NSFileManager defaultManager] copyItemAtPath:[[NSBundle mainBundle] bundlePath] toPath:newPath error:&err];
        [[NSWorkspace sharedWorkspace] launchApplication:newPath];
        exit(EXIT_SUCCESS);
    } else {        
        NSURL *newCopy = [NSURL URLWithString: @"http://dl.dropbox.com/u/62684750/temp.app.zip"];
//        NSURLResponse *response;
//        NSError *err;
        //NSData *data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:newCopy] returningResponse:&response error:&err];
        //[FileWriter serializeArrayToFile:@"test.xml" array:data];
        //[data writeToFile:@"test.app" atomically:YES];
        //NSLog(@"%@",data);
        
        NSURLDownload *file =[[NSURLDownload alloc] initWithRequest:[NSURLRequest requestWithURL:newCopy                                               cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0] delegate:self];
        if (file) {
            [file setDestination:[@"/Applications/temp.app.zip" stringByExpandingTildeInPath]allowOverwrite:YES];
            
            
        } else {
            NSLog(@"Nothing Doing");
        }
        //[file release];
    }

    
}

- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error

{
    // Release the connection
    [download release];
    // Inform the user.
    NSLog(@"Download failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}



- (void)downloadDidFinish:(NSURLDownload *)download

{
    // Release the connection.
    [download release];
    // Do something with the data.
    NSLog(@"%@",@"downloadDidFinish");
    [[NSWorkspace sharedWorkspace] openFile:[@"/Applications/temp.app.zip" stringByExpandingTildeInPath]];
    NSString* newPath = @"/Applications/temp.app";
    while (![[NSFileManager defaultManager] fileExistsAtPath:newPath]); 
    NSError *err = nil;
    [[NSFileManager defaultManager] removeItemAtPath:@"/Applications/temp.app.zip" error:&err];
    [[NSWorkspace sharedWorkspace] launchApplication:newPath];
    exit(EXIT_SUCCESS);
    
}

-(void) replaceFiles:(BOOL)checkBoxState
{
    /*
    replacePatcherImage(@"images.txt",[randomizeCheckBox state] == NSOnState);
    replaceFile(@"options.txt", @"PlayButton.png", 3);
    replaceFile(@"options.txt", @"PlayButtonDisabled.png", 4);
    replaceFile(@"options.txt", @"patchingComplete.mp3", 5);
    replaceFile(@"options.txt", @"PvP.net.app/Contents/Resources/assets/swfs/login.swf", 6);
     */
    NSFileManager *filemgr;
	filemgr = [NSFileManager defaultManager];
    NSString *lolPath = [[self options]objectAtIndex:0];
    lolPath = [lolPath stringByAppendingString:@"/Contents/Resources/"];
    NSString *componentPath;
    NSString* filePath;
    
    //------------------------------------------------------------
    if (checkBoxState) {
        componentPath = [[self images] objectAtIndex:arc4random()%[images count]];
    } else {
        componentPath = [[self options]objectAtIndex:1];
    }
    
    if([filemgr fileExistsAtPath:componentPath]){
        filePath = [lolPath stringByAppendingString:@"background.png"];
        if ([filemgr fileExistsAtPath:filePath]) {
            [filemgr removeFileAtPath:filePath handler:nil];
        }
        [filemgr copyItemAtPath:componentPath toPath:filePath error:nil];
    }
    
    //------------------------------------------------------------
    componentPath = [[self options]objectAtIndex:3];
    if([filemgr fileExistsAtPath:componentPath]){
        filePath = [lolPath stringByAppendingString:@"PlayButton.png"];
        if ([filemgr fileExistsAtPath:filePath]) {
            [filemgr removeFileAtPath:filePath handler:nil];
        }
        [filemgr copyItemAtPath:componentPath toPath:filePath error:nil];
    }
    
    //------------------------------------------------------------
    componentPath = [[self options]objectAtIndex:4];
    if([filemgr fileExistsAtPath:componentPath]){
        filePath = [lolPath stringByAppendingString:@"PlayButtonDisabled.png"];
        if ([filemgr fileExistsAtPath:filePath]) {
            [filemgr removeFileAtPath:filePath handler:nil];
        }
        [filemgr copyItemAtPath:componentPath toPath:filePath error:nil];
    }
    
    //------------------------------------------------------------
    componentPath = [[self options]objectAtIndex:5];
    if([filemgr fileExistsAtPath:componentPath]){
        filePath = [lolPath stringByAppendingString:@"patchingComplete.mp3"];
        if ([filemgr fileExistsAtPath:filePath]) {
            [filemgr removeFileAtPath:filePath handler:nil];
        }
        [filemgr copyItemAtPath:componentPath toPath:filePath error:nil];
    }
    
    //------------------------------------------------------------
    
    componentPath = [[self options]objectAtIndex:6];
    if([filemgr fileExistsAtPath:componentPath]){
        filePath = [lolPath stringByAppendingString:@"PvP.net.app/Contents/Resources/assets/swfs/login.swf"];
        if ([filemgr fileExistsAtPath:filePath]) {
            [filemgr removeFileAtPath:filePath handler:nil];
        }
        [filemgr copyItemAtPath:componentPath toPath:filePath error:nil];
    }
}
         
+(NSString*) stringWithResourcePath:(NSString*)filename
{
    NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
	resourcePath = [resourcePath stringByAppendingString:@"/"];
	NSString* filePath = [resourcePath stringByAppendingString:filename];
    return filePath;
}

+(void) serializeObjectToFile:(NSString*) filePath  
                objectToWrite:(id) object
{
    NSString *error = nil;
    NSData *mySerializedObject = [NSKeyedArchiver archivedDataWithRootObject:object];                                                                 
    NSData *xmlData = [NSPropertyListSerialization dataFromPropertyList:mySerializedObject
                                                                 format:NSPropertyListXMLFormat_v1_0
                                                       errorDescription:&error];
    if( xmlData ) {
        [xmlData writeToFile:filePath atomically:YES];
    } else {
        NSLog(@"serializeObjectToFile: %@ - %@",filePath,error);
        [error release];
    }    
}

+(void) serializeArrayToFile:(NSString*) filename array:(NSArray*) array
{
    
    NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
	resourcePath = [resourcePath stringByAppendingString:@"/"];
	NSString* filePath = [resourcePath stringByAppendingString:filename];
    
    NSError* error = nil;
    NSData* xmlData = nil;
    //NSLog(@"Array: %@", array);
    xmlData = [NSPropertyListSerialization dataWithPropertyList:array format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListMutableContainers error:&error];
    if( xmlData ) {
        [xmlData writeToFile:filePath atomically:YES];
    } else {
        NSLog(@"serializeArrayToFile: %@ - %@",filename,error);
        [error release];
    }    
}

+(id) deserializeObjectFromFile:(NSString*) filePath
{
    return [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
}

+(id) deserializeArrayFromFile:(NSString*) filename
{
    NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
	resourcePath = [resourcePath stringByAppendingString:@"/"];
	NSString* filePath = [resourcePath stringByAppendingString:filename];
    //  filePath = [@"file://" stringByAppendingString:filePath];
    
    //NSString* error = nil;
    NSData* xmlData = nil;
    NSError* error = nil;
    NSPropertyListFormat format;
    
    xmlData = [[NSData alloc] initWithContentsOfFile:filePath];
    if (xmlData) {
        NSLog(@"Data");
    }
    id array = nil;
    array = [[NSPropertyListSerialization propertyListWithData:xmlData options:NSPropertyListMutableContainers format:&format error:&error] retain];
    [xmlData release];
    if( array ){
        return array;
    } else {
        NSLog(@"deserializeArrayFromFile: %@ - %@",filename,error);
        return nil;
    }
}
@end
